package com.hxzy.projectssmplus.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import com.hxzy.projectssmplus.conf.properties.HxzyProperties;
import com.hxzy.projectssmplus.vo.AjaxResult;

import lombok.extern.log4j.Log4j2;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.UUID;

/**
 * 图片上传
 */
@Log4j2
@RestController
public class ImageUploadController extends BaseController {

    //只支持上传类型
    private final String extsionClude = "jpg,gif,png,jpeg";

    @Autowired
    private HxzyProperties hxzyProperties;
    /**
     * 文件上传
     *
     * @param attach springmvc的文件解析器  ，默认只支持10MB
     * @return
     */
    @PostMapping(value = "/upload/image")
    public AjaxResult imageUploadToOSS(MultipartFile attach) {

        System.out.println(hxzyProperties.toString());
        AjaxResult ajaxResult = null;
        if (attach.isEmpty()) {
            ajaxResult = AjaxResult.error("文件不能为空");
            return ajaxResult;
        }

        String fileName= attach.getOriginalFilename();
        //获取后缀名
        if(fileName.lastIndexOf(".")==-1){
            ajaxResult = AjaxResult.error("文件格式不正确，只支持jpg,gif,png,jpeg");
            return ajaxResult;
        }
        //文件后缀名
        String extion=fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
        if(!Arrays.asList(extsionClude.split(",")).contains(extion)){
            ajaxResult = AjaxResult.error("文件格式不正确，只支持jpg,gif,png,jpeg");
            return ajaxResult;
        }

        //上传到阿里云oss
        String key= UUID.randomUUID().toString()+"."+extion;

        OSS ossClient = new OSSClientBuilder().build(this.hxzyProperties.getOssEndpoint(), this.hxzyProperties.getOssAccessKeyId(), this.hxzyProperties.getOssAccessKeySecret());

        // 判断Bucket是否存在。详细请参看“SDK手册 > Java-SDK > 管理Bucket”。
        // 链接地址是：https://help.aliyun.com/document_detail/oss/sdk/java-sdk/manage_bucket.html?spm=5176.docoss/sdk/java-sdk/init
        if (!ossClient.doesBucketExist(this.hxzyProperties.getOssBucketName())) {
            log.error("{},阿里云bucketName配置错误",this.hxzyProperties.getOssBucketName());
            ajaxResult = AjaxResult.error("阿里云bucketName配置错误");
            return ajaxResult;
        }

        try {
            //当图片大于1MB，就要处理了
            if(attach.getSize()>(1024l*1024)){
                BufferedImage bufferedImage = Thumbnails.of(attach.getInputStream()).scale(1.0f).outputQuality(0.6).asBufferedImage();
                InputStream  inputStream=bufferedImageToInputStream(bufferedImage,extion);
                ossClient.putObject(this.hxzyProperties.getOssBucketName(), "images/"+key,inputStream);
            }else{
                ossClient.putObject(this.hxzyProperties.getOssBucketName(), "images/"+key, attach.getInputStream());
            }

        } catch (IOException e) {
            log.error(e);
            ajaxResult = AjaxResult.error("文件上传失败");
            return ajaxResult;
        }

        //https://hxzy-bucket.oss-cn-chengdu.aliyuncs.com/images/key

        ajaxResult=AjaxResult.success();
        String url= this.hxzyProperties.getOssFrontImageUrl()+key;
        ajaxResult.put("url",url);
        return ajaxResult;
    }

    public InputStream bufferedImageToInputStream(BufferedImage image,String foratName){
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, foratName, os);
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            return input;
        } catch (IOException e) {
            log.error("提示:",e);
        }
        return null;
    }
}


